/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * com_distri_articulos_invefisico.java
 *
 * Created on 23/01/2012, 08:52:37 AM
 */

package sie_invdis;


import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

import java.text.ParseException;
import java.text.*;

/**
 *
 * @author Michelle
 */
public class com_distri_articulos_invefisico extends javax.swing.JFrame {

      private javax.swing.table.DefaultTableModel jtable_modelo;
       bd_conexion x = new bd_conexion();
    ResultSet rs = null;
    private SimpleDateFormat formateadoresta = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");

    /** Creates new form com_distri_articulos_invefisico */
    public com_distri_articulos_invefisico() {
        this.iniciar_modelo_de_tabla();
        initComponents();
        this.carga_datos("");
    }

private void iniciar_modelo_de_tabla()
    {

        jtable_modelo=new javax.swing.table.DefaultTableModel();//Creo el modelo
        jtable_modelo.addColumn("<html><b>Id/Status</b></html>");
        jtable_modelo.addColumn("<html><b>Descripcion</b></html>");
        jtable_modelo.addColumn("<html><b>Titulo Inventario</b></html>");
        jtable_modelo.addColumn("<html><b>F.Programada</b></html>");
        jtable_modelo.addColumn("<html><b>F.Aplicacion.</b></html>");
        jtable_modelo.addColumn("<html><b>C. Teorica</b></html>");
        jtable_modelo.addColumn("<html><b>C. Fisica</b></html>");
        jtable_modelo.addColumn("<html><b>Diferencia</b></html>");

    }
private void carga_datos(String busqueda)
    {
       String fechacat = "",fechallegatienda="",fechaentrega="";
       DecimalFormat miformat = new DecimalFormat("###,###,###,###");
       this.LimpiarJTable();
       Object[] fnewRow = new Object[8];
       //invoco al metodo que trae el recordset de datos
       rs = x.sieuno_executediversosv2("select * from x1distribucion_terminados_inven_programados(3,'"+busqueda+"','')  as (id integer,idcon smallint,fechaprog date,horaprog text,fechaaplica date,horaaplica text,fecharevi date,idempleelabora integer,idempleasuper integer,idgerente integer,idsuper integer,cantteo numeric,cantfis numeric, descripinve text,observa text,valorcongel smallint,idstatusconge smallint,descrpstatu character varying(40),descripcongela character varying(40),obsercongelar character varying(80),camponombrecongela character varying(25));",variables_global.getconexiongral());
        try
         {
            while (rs.next())
                {
                fnewRow[0]=rs.getString ("id")+":"+rs.getString ("descrpstatu");
                fnewRow[1]=rs.getString ("descripcongela");
                fnewRow[2]=rs.getString ("descripinve");
                fnewRow[3]="<html>"+this.fechaeuropea(rs.getString ("fechaprog"))+":<br>"+DiaSemana(this.fechaeuropea(rs.getString ("fechaprog")))+" "+rs.getString ("horaprog")+"</html>";
                if(rs.getString("fechaaplica") != null)
                        {
                           fechallegatienda="<html>"+ rs.getString("fechaaplica")+":<br>"+DiaSemana(rs.getString ("fechaaplica"))+" "+rs.getString ("horaaplica")+"</html>";
                        }
                 fnewRow[4]=fechallegatienda;
                 fnewRow[5]=miformat.format(rs.getFloat("cantteo"));
                 fnewRow[6]=miformat.format(rs.getFloat("cantfis"));
                 fnewRow[7]=miformat.format(rs.getFloat("cantfis")-rs.getFloat("cantteo"));
                 jtable_modelo.addRow(fnewRow);

                }

        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }

        this.cambiartamanofilas();
      }

  private void LimpiarJTable()
 {
     //limpiar la tabla
    while(jtable_modelo.getRowCount()>0)jtable_modelo.removeRow(0);
 }
  private void cambiartamanofilas()
 {
           int numerofilas=this.jtable_modelo.getRowCount();

             for(int i = 0 ;i < numerofilas; i++)
                {
                     jt_catinveprogramados.setRowHeight(i, 30);
                }
  }
  private String  fechaeuropea(String fecha) {

         //resibe cadena de fecha en formato americano yyyy-MM-dd
        java.util.Date fechaestaeuropa=null;
       SimpleDateFormat formateadorestaeuropa = new SimpleDateFormat("dd-MM-yyyy");
       String cadenafecha="";
        try
         {
          fechaestaeuropa = formateadoresta.parse(fecha);
         }
        catch (ParseException e)
          {
             //Error, la cadena de texto no se puede convertir en fecha.
          }
       cadenafecha= formateadorestaeuropa.format(fechaestaeuropa);
       return cadenafecha;

    }
  private String DiaSemana(String fe) {
         String dia = "";
       java.util.Date fecha=null;
         try
            {
             fecha = formateador.parse(fe);

           }
        catch (ParseException e)
            {
            //Error, la cadena de texto no se puede convertir en fecha.
            }
        Calendar cal= Calendar.getInstance();
        cal.setTime(fecha);
        //ojo para establecer o recetear cada parte de la fecha por separado
        //cal.set(Calendar.YEAR, fecha.getYear());
        //cal.set(Calendar.MONTH, fecha.getMonth());
        //cal.set(Calendar.DAY_OF_MONTH, fecha.getDay());
        int diaInt = cal.get(Calendar.DAY_OF_WEEK);
        switch (diaInt) {
            case 1:
                dia = "Domingo";
                break;
            case 2:
                dia = "Lunes";
                break;
            case 3:
                dia = "Martes";
                break;
            case 4:
                dia = "Miercoles";
                break;
            case 5:
                dia = "Jueves";
                break;
            case 6:
                dia = "Viernes";
                break;
            case 7:
                dia = "Sabado";
                break;

        }
        return dia;
    }


 private  void ayuda()
            {
                String punto1="1.-Detalle de Recepcion de Mercancia, cada opcion se autodescribe brevemente\n";
                String punto2="  2.- Cada Boton tiene Una letra Resaltada el cual indica su metodo abreviado uselo si desea mayor rapides ( ejemplo Alt+a tendra ayuda automaticamente)\n";
                String punto3="  3.- la opcion guardar esta activada para Recepcionar este documento Incluyendo Diferencias si no ingresa diferencias, el sistema guardara el documento como correcto\n";
                JOptionPane.showMessageDialog(null,punto1+punto2+punto3, "Sistema Integral(Detalle Recepcion) : Ayuda",1);
            }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jt_catinveprogramados = new javax.swing.JTable()
        {
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        }
        ;
        jPanel1 = new javax.swing.JPanel();
        jbtn_agregar = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jmni_salir = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jmni_escape = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sie_invdis.Sie_invdisApp.class).getContext().getResourceMap(com_distri_articulos_invefisico.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jt_catinveprogramados.setModel(this.jtable_modelo);
        jt_catinveprogramados.setName("jt_catinveprogramados"); // NOI18N
        jt_catinveprogramados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jt_catinveprogramadosMouseClicked(evt);
                if(evt.getClickCount() >= 2)
                {
                    dioclick(evt);
                    //System.out.println(" double click" );

                }
            }
        });
        jScrollPane1.setViewportView(jt_catinveprogramados);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 907, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE)
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.setName("jPanel1"); // NOI18N

        jbtn_agregar.setIcon(resourceMap.getIcon("jbtn_agregar.icon")); // NOI18N
        jbtn_agregar.setText(resourceMap.getString("jbtn_agregar.text")); // NOI18N
        jbtn_agregar.setName("jbtn_agregar"); // NOI18N
        jbtn_agregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_agregarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jbtn_agregar)
                .addContainerGap(766, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jbtn_agregar)
        );

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        jmni_salir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
        jmni_salir.setIcon(resourceMap.getIcon("jmni_salir.icon")); // NOI18N
        jmni_salir.setText(resourceMap.getString("jmni_salir.text")); // NOI18N
        jmni_salir.setName("jmni_salir"); // NOI18N
        jmni_salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmni_salirActionPerformed(evt);
            }
        });
        jMenu1.add(jmni_salir);

        jMenuBar1.add(jMenu1);

        jMenu2.setText(resourceMap.getString("jMenu2.text")); // NOI18N
        jMenu2.setName("jMenu2"); // NOI18N

        jmni_escape.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        jmni_escape.setText(resourceMap.getString("jmni_escape.text")); // NOI18N
        jmni_escape.setName("jmni_escape"); // NOI18N
        jmni_escape.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmni_escapeActionPerformed(evt);
            }
        });
        jMenu2.add(jmni_escape);

        jMenuBar1.add(jMenu2);

        jMenu3.setText(resourceMap.getString("jMenu3.text")); // NOI18N
        jMenu3.setName("jMenu3"); // NOI18N
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(86, 86, 86)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jmni_salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmni_salirActionPerformed
        // TODO add your handling code here:
    if(JOptionPane.showConfirmDialog(null, "Realmente Desea Salir?")==0)
        {
            this.dispose();
        }
}//GEN-LAST:event_jmni_salirActionPerformed

    private void jbtn_agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_agregarActionPerformed
        // TODO add your handling code here:
        com_distri_articulos_invefisico_programar cdaip=new com_distri_articulos_invefisico_programar();
        cdaip.pack();
        cdaip.setVisible(true);
}//GEN-LAST:event_jbtn_agregarActionPerformed

    private void jmni_escapeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmni_escapeActionPerformed
        // TODO add your handling code here:
        this.jmni_salirActionPerformed(evt);
    }//GEN-LAST:event_jmni_escapeActionPerformed
private void jt_catinveprogramadosMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
    }
private void dioclick(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
         System.out.println("dio doble  click");
         int fila = jt_catinveprogramados.getSelectedRow();
         String idcadena[]=this.jt_catinveprogramados.getValueAt(fila, 0).toString().split(":");
         //JFrame mainFrame = Sie_invdisApp.getApplication().getMainFrame();
         com_distri_articulos_invefisico_detalle fcdaifd=new com_distri_articulos_invefisico_detalle(Integer.valueOf(idcadena[0]),0);
         fcdaifd.pack();
         fcdaifd.setVisible(true);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new com_distri_articulos_invefisico().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtn_agregar;
    private javax.swing.JMenuItem jmni_escape;
    private javax.swing.JMenuItem jmni_salir;
    private javax.swing.JTable jt_catinveprogramados;
    // End of variables declaration//GEN-END:variables

}
